﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DataCentral.UsecaseControllers;
using DevExpress.XtraEditors;
using DataCentral.Dataset;
using CommonData;

namespace DataCentral.Forms
{
    public partial class TablesConfigurationForm : CommonData.CommonChildForm
    {
        private SynchronizeUsecase _UCSynchronize;
        private DataTable tblDBConfig;
        private bool _IsEdit = false;
        private DataCentralDataset.TablesConfigurationRow _DRTablesConfig;
        private DataTable _TBLSourceCol;
        private DataTable _TBLDestCol;
        private DataCentralDataset _DSCental;

        public TablesConfigurationForm(SynchronizeUsecase ucSynchronize, DataCentralDataset dsCentral, bool isEdit, DataCentralDataset.TablesConfigurationRow drTablesConfig)
        {
            InitializeComponent();
            _UCSynchronize = ucSynchronize;
            _DSCental = dsCentral;
            _IsEdit = isEdit;
            _DRTablesConfig = drTablesConfig;
        }

        private void InitDataOnForm()
        {
            if (_IsEdit && _DRTablesConfig != null)
            {
                iluSConfig.EditValue = _DRTablesConfig.SourceConfigID;
                iluDConfig.EditValue = _DRTablesConfig.DestConfigID;
                txtConfigName.Text = _DRTablesConfig.ConfigName;
                iluSTable.Text = _DRTablesConfig.SourceTable;
                iluDTable.Text = _DRTablesConfig.DestTable;
                chkUnicode.Checked = _DRTablesConfig.ConvertUnicode;
                rdgSynType.SelectedIndex = _DRTablesConfig.IsAllData ? 0 : 1;

                pnDateTime.Enabled = rdgSynType.SelectedIndex ==1;
                iluColChanged.Enabled = pnDateTime.Enabled;
                if (rdgSynType.SelectedIndex == 1)
                {
                    iluColChanged.Text = _DRTablesConfig.TrackingChangeField;
                    dtpFromDate.DateTime = _DRTablesConfig.FromDate;
                    dtpToDate.DateTime = _DRTablesConfig.ToDate;
                }
                
                chklPKs.Text = _DRTablesConfig.PrimaryKeys;
                chkConvert.Text = _DRTablesConfig.ConvertKeys;
                daConfigDetail.Fill(_DSCental.TablesConfigurationDetail, _DRTablesConfig.ConfigID);
                daTableFK.Fill(_DSCental.TableConfigForeignKey, _DRTablesConfig.ConfigID);
            }
            else
            {
                iluSConfig.EditValue = null;
                iluDConfig.EditValue = null;
                txtConfigName.Text = string.Empty;
                iluSTable.Text = string.Empty;
                iluDTable.Text = string.Empty;
                chkUnicode.Checked = true;
                iluColChanged.Text = string.Empty;
                chklPKs.Text = string.Empty;
                chkConvert.Text = string.Empty;
                _DSCental.TablesConfigurationDetail.Clear();
                _DSCental.TableConfigForeignKey.Clear();
            }
            bsConfigDetail.DataSource = _DSCental;
            bsTableFK.DataSource = _DSCental;
            bsConfigDetail.DataMember = "TablesConfigurationDetail";
            bsTableFK.DataMember = "TableConfigForeignKey";
        }

        private bool IsExistColumnInSource(string colName)
        {
            for (int i = 0; i < _TBLSourceCol.Rows.Count; i++)
            {
                if (_TBLSourceCol.Rows[i]["COLUMN_NAME"].ToString().Trim().ToUpper().Equals(colName.ToUpper()))
                {
                    return true;
                }
            }
            return false;
        }

        private void GenerateColumns()
        {
            bool isExist = false;
            int iCount = _DSCental.TablesConfigurationDetail.Rows.Count;
            if (chkClearColumn.Checked)
            {
                while (iCount > 0)
                {
                    _DSCental.TablesConfigurationDetail.Rows[iCount-1].Delete();
                    iCount--;
                }
                for (int i = 0; i < _TBLDestCol.Rows.Count; i++)
                {
                    DataCentralDataset.TablesConfigurationDetailRow drNew = _DSCental.TablesConfigurationDetail.NewTablesConfigurationDetailRow();
                    drNew.ConfigID = _DRTablesConfig.ConfigID;
                    drNew.DestField = _TBLDestCol.Rows[i]["COLUMN_NAME"].ToString().Trim();
                    drNew.DestFieldType = _TBLDestCol.Rows[i]["DATA_TYPE"].ToString().Trim();
                    if (chkAutoDest.Checked && IsExistColumnInSource(drNew.DestField))
                    {
                        drNew.SourceField = drNew.DestField;
                        drNew.SourceFieldType = drNew.DestFieldType;
                    }
                    else
                    {
                        drNew.SourceField = string.Empty;
                        drNew.SourceFieldType = string.Empty;
                    }
                    _DSCental.TablesConfigurationDetail.AddTablesConfigurationDetailRow(drNew);
                }
            }
            else
            {
                for (int i = 0; i < _TBLDestCol.Rows.Count; i++)
                {
                    isExist = false;
                    foreach (DataCentralDataset.TablesConfigurationDetailRow drConfigDetail in _DSCental.TablesConfigurationDetail)
                    {
                        if (!drConfigDetail.IsSourceFieldNull() && drConfigDetail.SourceField.Trim().ToUpper().Equals(_TBLSourceCol.Rows[i]["COLUMN_NAME"].ToString().Trim().ToUpper()))
                        {
                            isExist = true;
                            break;
                        }
                    }
                    if (!isExist)
                    {
                        DataCentralDataset.TablesConfigurationDetailRow drNew = _DSCental.TablesConfigurationDetail.NewTablesConfigurationDetailRow();
                        drNew.ConfigID = _DRTablesConfig.ConfigID;
                        drNew.DestField = _TBLDestCol.Rows[i]["COLUMN_NAME"].ToString().Trim();
                        drNew.DestFieldType = _TBLDestCol.Rows[i]["DATA_TYPE"].ToString().Trim();
                        if (chkAutoDest.Checked && IsExistColumnInSource(drNew.DestField))
                        {
                            drNew.SourceField = drNew.DestField;
                            drNew.SourceFieldType = drNew.DestFieldType;
                        }
                        else
                        {
                            drNew.SourceField = string.Empty;
                            drNew.SourceFieldType = string.Empty;
                        }
                        _DSCental.TablesConfigurationDetail.AddTablesConfigurationDetailRow(drNew);

                    }
                }
            }
            gridColumn.RefreshDataSource();
        }

        private void SaveTablesConfigToDatabase()
        {
            if (!_IsEdit || _DRTablesConfig == null)
            {
                _DRTablesConfig = _DSCental.TablesConfiguration.NewTablesConfigurationRow();
            }
            _DRTablesConfig.SourceConfigID = Convert.ToInt32(iluSConfig.EditValue);
            _DRTablesConfig.DestConfigID = Convert.ToInt32(iluDConfig.EditValue) ;
            _DRTablesConfig.ConfigName = txtConfigName.Text ;
            _DRTablesConfig.SourceTable = iluSTable.Text;
            _DRTablesConfig.DestTable= iluDTable.Text ;
            _DRTablesConfig.IsAllData = rdgSynType.SelectedIndex == 0;
            _DRTablesConfig.TrackingChangeField = iluColChanged.Text;
            _DRTablesConfig.FromDate = dtpFromDate.DateTime;
            _DRTablesConfig.ToDate = dtpToDate.DateTime;
            _DRTablesConfig.ConvertUnicode = chkUnicode.Checked ;
            _DRTablesConfig.TrackingChangeField = iluColChanged.Text;
            _DRTablesConfig.PrimaryKeys = chklPKs.Text;
            _DRTablesConfig.ConvertKeys = chkConvert.Text;

            if (!_IsEdit || _DRTablesConfig == null)
            {
                _DSCental.TablesConfiguration.AddTablesConfigurationRow(_DRTablesConfig);
            }
            try
            {

                daTablesConfig.Update(_DSCental.TablesConfiguration);
                _IsEdit = true;
            }
            catch (Exception exp)
            {

            }
        }

        private void TablesConfigurationForm_Load(object sender, EventArgs e)
        {
            dtpFromDate.DateTime = DateTime.Now;
            dtpToDate.DateTime = DateTime.Now;
            ValueListClass clValueList = new ValueListClass();
            tblDBConfig = clValueList.GetDatabaseConfigList();
            iluSConfig.Properties.DataSource = tblDBConfig;
            iluDConfig.Properties.DataSource = tblDBConfig;
            if (tblDBConfig.Rows.Count > 0) iluDConfig.EditValue = 1;
            //cbbDatatype.Items.Clear();
            //foreach (string strType in _UCSynchronize.GetDatatypeList())
            //{
            //    cbbDatatype.Items.Add(strType);
            //}
            InitDataOnForm();
        }

        private void GetTableList(string database, ComboBoxEdit cbbTables)
        {
            DataTable tblTables = _UCSynchronize.GetTableList(database);
            
        }

        private void iluSConfig_EditValueChanged(object sender, EventArgs e)
        {
            if (iluSConfig.EditValue != null)
            {
                DataRow[] lstSelect = tblDBConfig.Select("ConfigID = " + iluSConfig.EditValue.ToString());
                if (lstSelect.Length > 0)
                {
                    txtSServer.Text = lstSelect[0]["Datasource"].ToString();
                    cbbSDatabase.Text = lstSelect[0]["InitCatalog"].ToString();
                    rdgSConnect.SelectedIndex = Convert.ToBoolean(lstSelect[0]["IntegratedSecurity"].ToString()) ? 0 : 1;
                    txtSLogin.Text = lstSelect[0]["UserID"].ToString();
                    txtSPassword.Text = CommonFunctions.DecodeFrom64(lstSelect[0]["Password"].ToString());
                    txtSConnection.Text = lstSelect[0]["ConnectionString"].ToString();
                    iluSTable.Properties.DataSource = _UCSynchronize.GetTableList(cbbSDatabase.Text);
                }
            }
        }

        private void iluDConfig_EditValueChanged(object sender, EventArgs e)
        {
            if (iluDConfig.EditValue != null)
            {
                DataRow[] lstSelect = tblDBConfig.Select("ConfigID = " + iluDConfig.EditValue.ToString());
                if (lstSelect.Length > 0)
                {
                    txtDServer.Text = lstSelect[0]["Datasource"].ToString();
                    cbbDDatabase.Text = lstSelect[0]["InitCatalog"].ToString();
                    rdgDConnect.SelectedIndex = Convert.ToBoolean(lstSelect[0]["IntegratedSecurity"].ToString()) ? 0 : 1;
                    txtDLogin.Text = lstSelect[0]["UserID"].ToString();
                    txtDPassword.Text = CommonFunctions.DecodeFrom64(lstSelect[0]["Password"].ToString());
                    txtDConnection.Text = lstSelect[0]["ConnectionString"].ToString();
                    iluDTable.Properties.DataSource = _UCSynchronize.GetTableList(cbbDDatabase.Text);
                    iluDestTable.DataSource = iluDTable.Properties.DataSource;
                }
            }
        }

        private void rdgSynType_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnDateTime.Enabled = rdgSynType.SelectedIndex == 1;
            iluColChanged.Enabled = rdgSynType.SelectedIndex == 1;
        }

        private void iluSTable_EditValueChanged(object sender, EventArgs e)
        {
            if (iluSTable.EditValue != null)
            {
                cbbSColumn.Items.Clear();
                _TBLSourceCol= _UCSynchronize.GetColumnList(txtSConnection.Text.Trim(),iluSTable.EditValue.ToString().Trim());
                for (int i = 0; i < _TBLSourceCol.Rows.Count; i++)
                {
                    cbbSColumn.Items.Add(_TBLSourceCol.Rows[i]["COLUMN_NAME"].ToString().Trim());
                }
                iluColChanged.Properties.DataSource = _TBLSourceCol;
                chklPKs.Properties.DataSource = _TBLSourceCol;
            }
        }

        private void iluDTable_EditValueChanged(object sender, EventArgs e)
        {
            if (iluDTable.EditValue != null)
            {
                cbbDColumns.Items.Clear();
                iluDestField.Items.Clear();
                _TBLDestCol= _UCSynchronize.GetColumnList(txtDConnection.Text.Trim(), iluDTable.EditValue.ToString().Trim());
                for (int i = 0; i < _TBLDestCol.Rows.Count; i++)
                {
                    cbbDColumns.Items.Add(_TBLDestCol.Rows[i]["COLUMN_NAME"].ToString().Trim());
                    iluDestField.Items.Add(_TBLDestCol.Rows[i]["COLUMN_NAME"].ToString().Trim());
                }
                chkConvert.Properties.DataSource = _TBLDestCol;
            }
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            if((MessageClass.ShowQuestionMessage("Chọn chức năng này để tự động chọn cột giữa bảng nguồn và bảng đích")==DialogResult.Yes))
            {
                SaveTablesConfigToDatabase();
                GenerateColumns();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            SaveTablesConfigToDatabase();
            daConfigDetail.Update(_DSCental.TablesConfigurationDetail);
            daTableFK.Update(_DSCental.TableConfigForeignKey);
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            SynchronizeUsecase _UCSynchronize = new SynchronizeUsecase();
            _UCSynchronize.SynchronizeAllDataToDestTable(_DRTablesConfig.ConfigID, txtSConnection.Text, (int)iluSConfig.EditValue, iluSTable.Text,iluDTable.Text, chkClearBeforeSync.Checked,rdgSynType.SelectedIndex ==0);
            if (chkShowResult.Checked)
            {
                AfterSyncMasterForm frmSyncMaster = new AfterSyncMasterForm(iluDTable.Text);
                frmSyncMaster.ShowDialog();
            }

        }

        private void viewColumn_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (viewColumn.GetFocusedDataRow() is DataCentralDataset.TablesConfigurationDetailRow)
            {
                if (_DRTablesConfig.ConfigID <= 0)
                    SaveTablesConfigToDatabase();
                ((DataCentralDataset.TablesConfigurationDetailRow)viewColumn.GetFocusedDataRow()).ConfigID = _DRTablesConfig.ConfigID;
            }
        }

        private void viewTableFK_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (viewTableFK.GetFocusedDataRow() is DataCentralDataset.TableConfigForeignKeyRow)
            {
                if (_DRTablesConfig.ConfigID <= 0)
                    SaveTablesConfigToDatabase();
                ((DataCentralDataset.TableConfigForeignKeyRow)viewTableFK.GetFocusedDataRow()).ConfigID = _DRTablesConfig.ConfigID;
            }
        }
    }
}
